package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.utils.RedisUtils;
import com.qf.vo.Msg;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

//用户 控制器层
@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired  //验证码存入redis中
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisUtils redisUtils;
    /**
     * 用户登录
     * 返回json
     * @param user
     * @return
     */
    @PostMapping("/userLogin")
    public Msg userLogin(@RequestBody User user, HttpServletRequest request){
        /* String verifyCode = (String)request.getSession().getAttribute("verifyCode");*/
        Msg msg = new Msg();
        /*  if(verifyCode.equals(user.getU_code())) {*/
        System.out.println("AAAAAAAAAAAA==========================="+user);
        User user1 = userService.userLogin(user);
        if (user1 != null) {
            request.getSession().setAttribute("uId", user1.getU_id());
            redisUtils.set("uId",user1.getU_id());
            msg.setMsg("ok");
        } else {
            msg.setMsg("no");
        }
        /* }*/
        return msg;
    }

    /**
     * 获取验证码
     * @param u_phone
     * @param request
     * @return
     */
    @GetMapping("/getCode/{u_phone}")
    public Msg getCode(@PathVariable("u_phone") String u_phone, HttpServletRequest request){
        //去验证 获取验证码  返回来字符串 存redis中  为注册获取和页面传来对比使用
        String getCode = userService.getCode(u_phone, request);
        redisTemplate.opsForValue().set(u_phone,getCode);
        Msg msg = new Msg();
        if(getCode!=null){
            msg.setMsg("ok");
        }else {
            msg.setMsg("no");
        }
        return msg;
    }


    @RequestMapping("/phoneMsgTest/{number}")
    public Object  phoneMsgTest(HttpServletRequest request,@PathVariable("number") String number){
        try {
            ZhenziSmsClient client = new ZhenziSmsClient(
                    "https://sms_developer.zhenzikj.com",
                    "106450",
                    "817648c2-9bb1-487d-8c29-ef79dcb7a74d");
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("templateId", "1240");
            params.put("number", number);
            // start
            String[] templateParams = new String[2];
            templateParams[0] = verifyCode;
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            // end
            String result = client.send(params);
            System.out.println(result);
            JSONObject json = null;
            json = JSONObject.parseObject(result);
            if(json.getIntValue("code") != 0){//发送短信失败
                System.out.println("发送短信失败");
                return "fail";
            }
            //将验证码存到session中,同时存入创建时间
            //以json存放，这里使用的是阿里的fastjson
            HttpSession session = request.getSession();
            json = new JSONObject();
            json.put("number", number);
            json.put("verifyCode", verifyCode);
            json.put("createTime", System.currentTimeMillis());
            // 将认证码存入SESSION，以便前台获取正确的验证码，和用户输入的验证码比较
            request.getSession().setAttribute("verifyCode", json);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/userRegister")
    public Msg userRegister(@RequestBody User user, HttpServletRequest request){
        //先和redis中的验证码比较,比较成功之后去后台注册
//        String code = (String)request.getSession().getAttribute(user.getU_phone());
        String code = (String)redisTemplate.opsForValue().get(user.getU_phone());
        Msg msg = new Msg();
        if(code.equals(user.getU_code())){
            int res = userService.register(user);
            if(res>0){
                msg.setMsg("ok");
            }else {
                msg.setMsg("no");
            }
        }
        return msg;
    }
}
